package com.meet.app;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.text.TextUtils;
import android.view.View;

import androidx.core.view.WindowCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.gson.Gson;
import com.meet.app.databinding.ActivityMainBinding;
import com.meet.app.fragment.ChatFragment;
import com.meet.app.fragment.LiveFragment;
import com.meet.app.fragment.MeFragment;
import com.meet.app.fragment.SquareFragment;
import com.meet.app.fragment.StarFragment;
import com.meet.app.service.CloudService;
import com.meet.app.ui.FirstUploadActivity;
import com.meet.app.ui.LoginActivity;
import com.meet.framework.base.BaseUIActivity;
import com.meet.framework.bmob.BmobManager;
import com.meet.framework.bmob.IMUser;
import com.meet.framework.entity.Constants;
import com.meet.framework.gson.TokenBean;
import com.meet.framework.java.SimulationData;
import com.meet.framework.manager.DialogManager;
import com.meet.framework.manager.HttpManager;
import com.meet.framework.manager.MediaPlayerManager;
import com.meet.framework.utils.LogUtils;
import com.meet.framework.utils.SpUtils;
import com.meet.framework.view.DialogView;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseUIActivity  implements  View.OnClickListener{

    //星球
    private ImageView iv_star;
    private TextView tv_star;
    private LinearLayout ll_star;
    private StarFragment mStarFragment = null;
    private FragmentTransaction mStarTransaction = null;

    //广场
    private ImageView iv_square;
    private TextView tv_square;
    private LinearLayout ll_square;
    private SquareFragment mSquareFragment = null;
    private FragmentTransaction mSquareTransaction = null;


    //直播
    private ImageView iv_live;
    private TextView tv_live;
    private LinearLayout ll_live;
    private LiveFragment mLiveFragment = null;
    private FragmentTransaction mLiveTransaction = null;

    //聊天
    private ImageView iv_chat;
    private TextView tv_chat;
    private LinearLayout ll_chat;
    private ChatFragment mChatFragment = null;
    private FragmentTransaction mChatTransaction = null;

    //我的
    private ImageView iv_me;
    private TextView tv_me;
    private LinearLayout ll_me;
    private MeFragment mMeFragment = null;
    private FragmentTransaction mMeTransaction = null;

    private Disposable disposable;

    //跳转上传头像的回调code
    public static final  int UPLOAD_REQUEST_CODE=1002;
;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        LogUtils.i("hello world");
//        LogUtils.e("hello world");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    /**
     * 初始化View
     */
    private void initView() {
//        if(!checkPermissions(Manifest.permission.READ_PHONE_STATE)){
//            requestPermission(new String[]{Manifest.permission.READ_PHONE_STATE},1000);
//        }


//        request(1000, new OnPermissionsResult() {
//            @Override
//            public void OnSuccess() {
//                Toast.makeText(MainActivity.this, "申请成功",
//                            Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void OnFail(List<String> noPermissions) {
//                Toast.makeText(MainActivity.this, noPermissions.toString(),
//                        Toast.LENGTH_SHORT).show();
//            }
//        });
        //BmobManager.getInstance().addUpdateSet();

        requestPermiss();

        iv_star = (ImageView) findViewById(R.id.iv_star);
        tv_star = (TextView) findViewById(R.id.tv_star);
        ll_star = (LinearLayout) findViewById(R.id.ll_star);

        iv_square = (ImageView) findViewById(R.id.iv_square);
        tv_square = (TextView) findViewById(R.id.tv_square);
        ll_square = (LinearLayout) findViewById(R.id.ll_square);

        iv_live = (ImageView) findViewById(R.id.iv_live);
        tv_live = (TextView) findViewById(R.id.tv_live);
        ll_live = (LinearLayout) findViewById(R.id.ll_live);


        iv_chat = (ImageView) findViewById(R.id.iv_chat);
        tv_chat = (TextView) findViewById(R.id.tv_chat);
        ll_chat = (LinearLayout) findViewById(R.id.ll_chat);

        iv_me = (ImageView) findViewById(R.id.iv_me);
        tv_me = (TextView) findViewById(R.id.tv_me);
        ll_me = (LinearLayout) findViewById(R.id.ll_me);

        ll_star.setOnClickListener(this);
        ll_square.setOnClickListener(this);
        ll_live.setOnClickListener(this);
        ll_chat.setOnClickListener(this);
        ll_me.setOnClickListener(this);

        //设置文本
        tv_star.setText(getString(R.string.text_main_star));
        tv_square.setText(getString(R.string.text_main_square));
        tv_live.setText(getString(R.string.text_main_live));
        tv_chat.setText(getString(R.string.text_main_chat));
        tv_me.setText(getString(R.string.text_main_me));

        //初始化fragment
        initFragment();

        //切换默认的选项卡
        checkMainTab(0);
//
        //检查TOKEN
        checkToken();

        //模拟数据
//        SimulationData.testData();
    }

    /**
     * 检查TOKEN
     */
    private void checkToken() {
        LogUtils.i("checkToken");
//        if (mUploadView != null) {
//            DialogManager.getInstance().hide(mUploadView);
//        }
        //获取TOKEN 需要三个参数 1.用户ID 2.头像地址 3.昵称
        String token = SpUtils.getInstance().getString(Constants.SP_TOKEN, "");
        if (!TextUtils.isEmpty(token)) {
            //启动云服务去连接融云服务
            startCloudService();
        } else {
            //1.有三个参数
//            String tokenPhoto = BmobManager.getInstance().getUser().getTokenPhoto();
//            String tokenName = BmobManager.getInstance().getUser().getTokenNickName();
//            if (!TextUtils.isEmpty(tokenPhoto) && !TextUtils.isEmpty(tokenName)) {
//                //创建Token
//                createToken();
//            } else {
//                //创建上传提示框
//                createUploadDialog();
//            }
//            //创建上传提示框
//            createUploadDialog();
            createToken();
        }
    }

    /**
     * 启动云服务去连接融云服务
     */
    private void startCloudService() {
        LogUtils.i("startCloudService");
        startService(new Intent(this, CloudService.class));
//        //检查更新
//        new UpdateHelper(this).updateApp(null);
    }


    /**
     * 创建上传提示框
     */
    private void createUploadDialog() {
        final DialogView mUploadView = DialogManager.getInstance().initView(this, R.layout.dialog_first_upload);
        //外部点击不能消息
        mUploadView.setCancelable(false);
        ImageView iv_go_upload = mUploadView.findViewById(R.id.iv_go_upload);
        iv_go_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogManager.getInstance().hide(mUploadView);
                FirstUploadActivity.startActivity(MainActivity.this,UPLOAD_REQUEST_CODE);
            }
        });
        DialogManager.getInstance().show(mUploadView);
    }
    /**
     * 创建TOKEN
     */
    private void createToken() {
        LogUtils.i("createToken");
        /**
         * 1.去融云后台获取Token
         * 2.连接融云
         */
        final HashMap<String, String> map = new HashMap<>();
//        map.put("userId", BmobManager.getInstance().getUser().getObjectId());
//        map.put("name", BmobManager.getInstance().getUser().getTokenNickName());
//        map.put("portraitUri", BmobManager.getInstance().getUser().getTokenPhoto());
        map.put("userId", "123456");
        map.put("name", "11");
        map.put("portraitUri", "222");

        //通过OkHttp请求Token
        //异步请求，同步的方法
        disposable = Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                        //执行请求过程
                        String json = HttpManager.getInstance().postCloudToken(map);
                        LogUtils.i("json:" + json);
                        emitter.onNext(json);
                        emitter.onComplete();
                    }
                    //线程调度
                }).subscribeOn(Schedulers.newThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                            parsingCloudToken(s);
                    }
                }) ;

    }

    /**
     * 解析Token
     *
     * @param s
     */
    private void parsingCloudToken(String s) {
        try {
            LogUtils.i("parsingCloudToken:" + s);
            TokenBean tokenBean = new Gson().fromJson(s, TokenBean.class);
            if (tokenBean.getCode() == 200) {
                if (!TextUtils.isEmpty(tokenBean.getToken())) {
                    //保存Token
                    SpUtils.getInstance().putString(Constants.SP_TOKEN, tokenBean.getToken());
                    startCloudService();
                }
            } else if (tokenBean.getCode() == 2007) {
                Toast.makeText(this, "注册人数已达上限，请替换成自己的Key", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            LogUtils.i("parsingCloudToken:" + e.toString());
        }
    }


    /**
     * 请求权限
     */
    private void requestPermiss() {
        //危险权限
        if(!checkWindowPermissions()){
            requestWindowPermissions();
        }
        request(new OnPermissionsResult() {
            @Override
            public void OnSuccess() {

            }

            @Override
            public void OnFail(List<String> noPermissions) {
                Toast.makeText(MainActivity.this, noPermissions.toString(),
                        Toast.LENGTH_SHORT).show();
                LogUtils.i("noPermissions:" + noPermissions.toString());
            }
        });
    }



    /**
     * 初始化Fragment
     */
    private void initFragment() {

        //星球
        if (mStarFragment == null) {
            mStarFragment = new StarFragment();
            mStarTransaction = getSupportFragmentManager().beginTransaction();
            mStarTransaction.add(R.id.mMainLayout, mStarFragment);
            mStarTransaction.commit();
        }

        //广场
        if (mSquareFragment == null) {
            mSquareFragment = new SquareFragment();
            mSquareTransaction = getSupportFragmentManager().beginTransaction();
            mSquareTransaction.add(R.id.mMainLayout, mSquareFragment);
            mSquareTransaction.commit();
        }

        //直播
        if(mLiveFragment==null){
            mLiveFragment = new LiveFragment();
            mLiveTransaction = getSupportFragmentManager().beginTransaction();
            mLiveTransaction.add(R.id.mMainLayout, mLiveFragment);
            mLiveTransaction.commit();
        }

        //聊天
        if (mChatFragment == null) {
            mChatFragment = new ChatFragment();
            mChatTransaction = getSupportFragmentManager().beginTransaction();
            mChatTransaction.add(R.id.mMainLayout, mChatFragment);
            mChatTransaction.commit();
        }

        //我的
        if (mMeFragment == null) {
            mMeFragment = new MeFragment();
            mMeTransaction = getSupportFragmentManager().beginTransaction();
            mMeTransaction.add(R.id.mMainLayout, mMeFragment);
            mMeTransaction.commit();
        }
    }


    /**
     * 显示Fragment
     *
     * @param fragment
     */
    private void showFragment(Fragment fragment) {
        if (fragment != null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            hideAllFragment(transaction);
            transaction.show(fragment);
            transaction.commitAllowingStateLoss();
        }
    }

    /**
     * 隐藏所有的Fragment
     *
     * @param transaction
     */
    private void hideAllFragment(FragmentTransaction transaction) {
        if (mStarFragment != null) {
            transaction.hide(mStarFragment);
        }
        if (mSquareFragment != null) {
            transaction.hide(mSquareFragment);
        }
        if(mLiveFragment!=null){
            transaction.hide(mLiveFragment);
        }
        if (mChatFragment != null) {
            transaction.hide(mChatFragment);
        }
        if (mMeFragment != null) {
            transaction.hide(mMeFragment);
        }
    }


    /**
     * 切换主页选项卡
     *
     * @param index 0：星球
     *              1：广场
     *              2：聊天
     *              3：我的
     */
    private void checkMainTab(int index) {
        switch (index) {
            case 0:
                showFragment(mStarFragment);

                iv_star.setImageResource(R.drawable.img_star_p);
                iv_square.setImageResource(R.drawable.img_square);
                iv_live.setImageResource(R.drawable.img_live);
                iv_chat.setImageResource(R.drawable.img_chat);
                iv_me.setImageResource(R.drawable.img_me);

                tv_star.setTextColor(getResources().getColor(R.color.colorAccent));
                tv_square.setTextColor(Color.BLACK);
                tv_live.setTextColor(Color.BLACK);
                tv_chat.setTextColor(Color.BLACK);
                tv_me.setTextColor(Color.BLACK);

                break;
            case 1:
                showFragment(mSquareFragment);

                iv_star.setImageResource(R.drawable.img_star);
                iv_square.setImageResource(R.drawable.img_square_p);
                iv_live.setImageResource(R.drawable.img_live);
                iv_chat.setImageResource(R.drawable.img_chat);
                iv_me.setImageResource(R.drawable.img_me);

                tv_star.setTextColor(Color.BLACK);
                tv_square.setTextColor(getResources().getColor(R.color.colorAccent));
                tv_live.setTextColor(Color.BLACK);
                tv_chat.setTextColor(Color.BLACK);
                tv_me.setTextColor(Color.BLACK);

                break;
            case 2:
                showFragment(mLiveFragment);
                iv_star.setImageResource(R.drawable.img_star);
                iv_square.setImageResource(R.drawable.img_square);
                iv_live.setImageResource(R.drawable.img_live_p);
                iv_chat.setImageResource(R.drawable.img_chat);
                iv_me.setImageResource(R.drawable.img_me);

                tv_star.setTextColor(Color.BLACK);
                tv_square.setTextColor(Color.BLACK);
                tv_live.setTextColor(getResources().getColor(R.color.colorAccent));
                tv_chat.setTextColor(Color.BLACK);
                tv_me.setTextColor(Color.BLACK);

                break;
            case 3:
                showFragment(mChatFragment);

                iv_star.setImageResource(R.drawable.img_star);
                iv_square.setImageResource(R.drawable.img_square);
                iv_live.setImageResource(R.drawable.img_live);
                iv_chat.setImageResource(R.drawable.img_chat_p);
                iv_me.setImageResource(R.drawable.img_me);

                tv_star.setTextColor(Color.BLACK);
                tv_square.setTextColor(Color.BLACK);
                tv_live.setTextColor(Color.BLACK);
                tv_chat.setTextColor(getResources().getColor(R.color.colorAccent));
                tv_me.setTextColor(Color.BLACK);

                break;
            case 4:
                showFragment(mMeFragment);

                iv_star.setImageResource(R.drawable.img_star);
                iv_square.setImageResource(R.drawable.img_square);
                iv_live.setImageResource(R.drawable.img_live);
                iv_chat.setImageResource(R.drawable.img_chat);
                iv_me.setImageResource(R.drawable.img_me_p);

                tv_star.setTextColor(Color.BLACK);
                tv_square.setTextColor(Color.BLACK);
                tv_live.setTextColor(Color.BLACK);
                tv_chat.setTextColor(Color.BLACK);
                tv_me.setTextColor(getResources().getColor(R.color.colorAccent));

                break;
        }
    }

    /**
     * 防止重叠
     * 当应用的内存紧张的时候，系统会回收掉Fragment对象
     * 再一次进入的时候会重新创建Fragment
     * 非原来对象，我们无法控制，导致重叠
     *
     * @param fragment
     */
    @Override
    public void onAttachFragment(Fragment fragment) {
        if (mStarFragment != null && fragment instanceof StarFragment) {
            mStarFragment = (StarFragment) fragment;
        }
        if (mSquareFragment != null && fragment instanceof SquareFragment) {
            mSquareFragment = (SquareFragment) fragment;
        }
        if (mChatFragment != null && fragment instanceof ChatFragment) {
            mChatFragment = (ChatFragment) fragment;
        }
        if (mMeFragment != null && fragment instanceof MeFragment) {
            mMeFragment = (MeFragment) fragment;
        }
    }

    @Override
    public void onClick(View view) {
        int viewId=view.getId();
        if(viewId==R.id.ll_star){
            checkMainTab(0);
        }

        if(viewId==R.id.ll_square){
            checkMainTab(1);
        }
        if(viewId==R.id.ll_live){
            checkMainTab(2);
        }

        if(viewId==R.id.ll_chat){
            checkMainTab(3);
        }

        if(viewId==R.id.ll_me){
            checkMainTab(4);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(resultCode== Activity.RESULT_OK){
            if(requestCode==UPLOAD_REQUEST_CODE){
                //说明上传头像成功了
                checkToken();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            if (!disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }



    //    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode) {
//            case 1000:
//                // If request is cancelled, the result arrays are empty.
//                if (grantResults.length > 0 &&
//                        grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    // Permission is granted. Continue the action or workflow
//                    // in your app.
//                    Toast.makeText(MainActivity.this, "申请成功",
//                            Toast.LENGTH_SHORT).show();
//
//                }  else {
//                    // Explain to the user that the feature is unavailable because
//                    // the feature requires a permission that the user has denied.
//                    // At the same time, respect the user's decision. Don't link to
//                    // system settings in an effort to convince the user to change
//                    // their decision.
//                    Toast.makeText(MainActivity.this, "申请失败",
//                            Toast.LENGTH_SHORT).show();
//
//                }
//                return;
//        }
//        // Other 'case' lines to check for other
//        // permissions this app might request.
//    }
}